package com.hehe.controller;

import com.hehe.POJO.User;
import com.hehe.Repository.UserRepository;
import jakarta.annotation.Resource;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.regex.Pattern;

@Slf4j
@Controller
public class RegisterController {


    @Value("${config_file_name}")
    private String config_file_name;

    private static final Pattern USERNAME_PATTERN = Pattern.compile("^[a-zA-Z0-9]+$");

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserRepository userRepository;

    @GetMapping("/register")
    public String loginPage(HttpServletRequest request) {
        return "register/register.html";
    }


//    @ModelAttribute("loggedInUser")
//    public Tb_user getLoggedInUser(@CookieValue(value = "username", required = false) String username) {
//        if (username != null) {
//            // Simulate fetching user data from a service or database
//            Tb_user tb_user = new Tb_user();
//            tb_user.setUsername(username);
//            return tb_user;
//        }
//        return null;
//    }


    @PostMapping("/register")
    public String register(@RequestParam String username, @RequestParam String password, HttpServletResponse response, Model model) {
        // 检查用户名格式
        if (!isValidUsername(username)) {
            model.addAttribute("error", "用户名只能包含 数字 和 字母");
            return "register/register.html";
        }

        // 检查用户名是否已存在
        User existingUser = userRepository.findByUsername(username);
        if (existingUser != null) {
            model.addAttribute("error", "用户名已存在");
            return "register/register.html";
        }

        // 创建新用户
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(passwordEncoder.encode(password)); // 加密密码
        userRepository.save(newUser);

        // 设置登录 Cookie
        Cookie cookie = new Cookie("username", newUser.getUsername());
        cookie.setMaxAge(15 * 24 * 60 * 60); // 15 days
        response.addCookie(cookie);
        return "redirect:/";
    }

    // 验证用户名格式的方法
    private boolean isValidUsername(String username) {
        return USERNAME_PATTERN.matcher(username).matches();
    }


    @GetMapping("/register-success")
    public String homePage(HttpServletRequest request) {
//        Cookie[] cookies = request.getCookies();
//        if (cookies != null) {
//            for (Cookie cookie : cookies) {
//                if ("username".equals(cookie.getName())) {
//                    System.out.println("用户已登录，继续处理请求");
//                    return "login-success.html";
//                }
//            }
//        }
//        return "login.html";
        return "register/register-success.html";
    }


}



